package com.jiang.jetpackdemo.utils

import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.os.Environment
import android.os.StrictMode
import android.provider.MediaStore
import android.util.Log
import android.util.Size
import androidx.core.content.ContextCompat.getSystemService
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import com.jiang.jetpackdemo.database.FavoritesModelDao
import com.jiang.jetpackdemo.model.FavoritesModel
import com.jiang.jetpackdemo.model.NewsInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.time.format.DateTimeFormatter
import java.util.*


val timeFormatter by lazy {
    DateTimeFormatter.ofPattern(
        "yyyy-MM-dd-HH:mm:ss",
        Locale.CHINA
    ) /*等效于 SimpleDateFormat("yyyy-MM-dd-HH:mm:ss")*/
}

fun dp2px(context: Context, dp: Float): Int {
    val density = context.resources.displayMetrics.density
    return (dp * density + 0.5F).toInt()
}

fun createLocalFile(context: Context, name: String): File =
    File(
        context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath,
//        "jetpack_${timeFormatter.format(ZonedDateTime.now())}.jpeg"
        fixString(name)
    )

fun fixString(string: String) =
    string.replace("/", "").replace("\\", "").replace("http", "").replace(":", "")


suspend fun copyFile(source: File, target: File): File {
    return withContext(Dispatchers.IO) {
        val fileInputStream = FileInputStream(source)
        val fileOutputStream = FileOutputStream(target)
        val buffer = ByteArray(1024)
        while (fileInputStream.read(buffer) > 0) {
            fileOutputStream.write(buffer)
        }
        fileInputStream.close()
        fileOutputStream.close()
        return@withContext target
    }
}

suspend fun downloadImage(context: Context, url: String): File {
    return withContext(Dispatchers.IO) {
        Log.d("downloadImage", url)
        Log.d("downloadImage", fixString(url))
        Glide.with(context)
            .load(url)
            .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
            .get()
    }
}

fun shareFile(context: Context, path: String, isImage: Boolean): Boolean {
    return try {
        Intent().apply {
            action = Intent.ACTION_SEND
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
            putExtra(Intent.EXTRA_STREAM, Uri.fromFile(File(path)))
            type = if (isImage) "image/*" else "*/*"
            context.startActivity(Intent.createChooser(this, "分享"))
        }
        true
    } catch (e: Exception) {
        Log.e("shareImage", e.localizedMessage)
        false
    }
}

//报错：exposed beyond app through ClipData.Item.getUri，使用
fun exposedFileUri() {
    val builder = StrictMode.VmPolicy.Builder()
    StrictMode.setVmPolicy(builder.build())
    builder.detectFileUriExposure()
}

suspend fun saveImage(context: Context, url: String, onFinish: () -> Unit = {}) {
    withContext(Dispatchers.IO) {
        try {
            val downloadImage = downloadImage(context, url)
            Log.d("saveImage", "onSaveImage: ${downloadImage.absolutePath}")
            val copyFile = copyFile(downloadImage, createLocalFile(context, url))
            val absolutePath = copyFile.absolutePath
            Log.d("saveImage", "saveImageDone: $absolutePath")
            // 通知系统相册
            MediaStore.Images.Media.insertImage(
                context.contentResolver,
                absolutePath,
                copyFile.name,
                null
            )
            context.sendBroadcast(
                Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.parse("file://$absolutePath")
                )
            )
            onFinish()
        } catch (e: Exception) {
            Log.e("saveImage", e.localizedMessage, e)
        }


        // shareFile(context,absolutePath,true)
    }
}

fun hasSameFile(context: Context, fileName: String, isOutSize: Boolean): Boolean {
    val path = if (isOutSize) "${Environment.getExternalStorageDirectory().absolutePath}/Download"
    else context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath
    val file = File(Environment.getExternalStorageDirectory().absolutePath)
    val listFiles = file.listFiles()
    val fixString = fixString(fileName)
    Log.d("hasSameFile", file.absolutePath)
    listFiles.forEach {
        Log.d("hasSameFile", "FilesName: ${it.name}")
        if (it.name.contains(fileName)) return true
    }
    return false
}

suspend fun isAlreadyCollected(
    favoritesModel: FavoritesModel,
    favoritesModelDao: FavoritesModelDao
): Boolean {
    return withContext(Dispatchers.IO) {
        val queryAll = favoritesModelDao.queryAll()
        if (queryAll.isNotEmpty()) {
            queryAll.forEach {
                if (favoritesModel == it) return@withContext true
            }
        } else {
            return@withContext false
        }
        return@withContext false
    }
}

fun downloadFile(appContext: Context, url: String, fileName: String) {
    val downloadManager: DownloadManager =
        appContext.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    DownloadManager.Request(Uri.parse(url)).apply {
        setDestinationInExternalPublicDir("Download", fileName)
        downloadManager.enqueue(this)
    }
}

fun checkIsWifiConnected(appContext: Context): Boolean {
    val connectivityManager =
        appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    return connectivityManager.activeNetworkInfo.type == ConnectivityManager.TYPE_WIFI
}